<!-- 促销列表 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        </div>
        <!-- <div>
          <el-button icon="upload" @click="handleOpenImportDialog">导入</el-button>

          <el-button icon="download" @click="handleExport">导出</el-button>
        </div> -->
      </div>

      <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="促销时间" prop="promotionDateTime" align="center"></el-table-column>
        <el-table-column label="促销排序" prop="sort" align="center" />
        <!-- <el-table-column label="创建时间" prop="promotionDateTime" align="center" /> -->

        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              icon="edit"
              link
              size="small"
              @click="handleAddGoods(scope.row.id)"
            >
              添加商品
            </el-button>
            <el-button
              type="primary"
              icon="edit"
              link
              size="small"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="delete"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="店铺" prop="storeId">
          <el-select v-model="formData.storeId" placeholder="请选择店铺">
            <el-option
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="促销时间" prop="promotionDateTime">
          <el-date-picker
            v-model="formData.promotionDateTime"
            type="datetime"
            value-format="YYYY-MM-DD hh:mm:ss"
            placeholder="选择促销时间"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            placeholder="请输入分类编号"
            :min="1"
            :max="999999"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialog.visibleGoods" title="添加促销商品" width="500">
      <el-form ref="goodsRef" :model="formGoods" :rules="rulesGoods" label-width="80px">
        <el-form-item label="店铺" prop="storeId">
          <el-select v-model="formGoods.storeId" placeholder="请选择店铺">
            <el-option
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="goodsIdList">
          <el-select v-model="formGoods.goodsIdList" multiple filterable placeholder="请选择店铺">
            <el-option
              v-for="item in goodsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseGoodsDialog">取消</el-button>
          <el-button type="primary" @click="handleGoodsSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import PromotionAPI, { GoodsPageQuery } from "@/api/system/promotion.api";

import StoreAPI from "@/api/system/store.api";
import { ref, reactive, onMounted, watch } from "vue";
import GoodsAPI from "@/api/system/goods.api";

defineOptions({
  name: "Category",
  inheritAttrs: false,
});
const queryFormRef = ref();
const formRef = ref();
const goodsRef = ref();

const queryParams = reactive<GoodsPageQuery>({
  page: 1,
  pageSize: 10,
});

const dialog = reactive({
  visible: false,
  visibleGoods: false,
  title: "新增促销",
});

const formData = reactive<any>({
  sort: "",
  promotionDateTime: "",
  storeId: "",
});
const formGoods = reactive<any>({
  promotionSessionId: "",
  goodsIdList: [],
  storeId: "",
});

const rules = reactive({
  storeId: [{ required: true, message: "选择店铺", trigger: "blur" }],
  promotionDateTime: [{ required: true, message: "促销时间不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});
const rulesGoods = reactive({
  storeId: [{ required: true, message: "选择店铺", trigger: "blur" }],
  goodsIdList: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});

const pageData = ref<any[]>();
const selectIds = ref<any[]>();
const total = ref(0);
const loading = ref(false);

// 角色下拉数据源
const storeOptions = ref<OptionType[]>();
const goodsOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

function getList() {
  StoreAPI.getList({
    page: 1,
    pageSize: 999,
  }).then((data) => {
    console.log(data);
    storeOptions.value = data.map((item) => ({
      label: item.storeName,
      value: item.id,
    }));
  });
  GoodsAPI.getList({
    page: 1,
    pageSize: 999,
  }).then((data) => {
    console.log(data);
    goodsOptions.value = data.map((item) => ({
      label: item.goodsName,
      value: item.id,
    }));
  });
}

// 查询
function handleQuery() {
  loading.value = true;
  PromotionAPI.getList(queryParams)
    .then((data) => {
      console.log(data);
      pageData.value = data;
      total.value = data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}
async function handleAddGoods(id: string) {
  dialog.visibleGoods = true;
  formGoods.promotionSessionId = id;
}
/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改分类";
    //编辑
    PromotionAPI.detailInfo({ id: id }).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    // 新增

    dialog.title = "新增分类";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = undefined;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const id = formData.id;
      loading.value = true;
      if (id) {
        PromotionAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        PromotionAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

// 关闭弹窗
function handleCloseGoodsDialog() {
  dialog.visibleGoods = false;
  goodsRef.value.resetFields();
  goodsRef.value.clearValidate();
}

const handleGoodsSubmit = useDebounceFn(() => {
  goodsRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      PromotionAPI.addGoods(formGoods)
        .then(() => {
          ElMessage.success("新增成功");
          handleCloseGoodsDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 1000);

/**
 * 删除商品
 *
 * @param id  用户ID
 */
function handleDelete(id?: string) {
  ElMessageBox.confirm("确认删除商品?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      PromotionAPI.deleteByIds(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

onMounted(() => {
  getList();
  handleQuery();
});
</script>
